package br.com.andre.neo4j.model;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.tooling.GlobalGraphOperations;

public class UserDAO {
	private Connection conn;
	public UserDAO() {
		this.conn = new Connection();
	}
	// sem index
	public void createUser(UserTO user) {
		GraphDatabaseService graph = conn.newConnection();
		if (checkUser(user, graph)) {
			System.out.println("pode ser gravado");
			Transaction tx = graph.beginTx();
			try {
				Node userNode = graph.createNode();
				userNode.setProperty("login", user.getLogin());
				userNode.setProperty("name", user.getName());
				userNode.setProperty("password", user.getPassword());
				tx.success();
			} catch (Exception e) {
				tx.failure();
			} finally{
				tx.finish();
			}
		}else{
			System.out.println("Não pode ser gravado");
		}
		
		graph.shutdown();
	}
	
	private boolean checkUser(UserTO user , GraphDatabaseService graph){
		for (Node userNode : GlobalGraphOperations.at(graph).getAllNodes()) {
			if (userNode.hasProperty("login")) {
				if (userNode.getProperty("login").equals(user.getLogin())) {
					return false;
				}
			}
		}
		return true;
	}
	
	// com index
	
	public void createUserIndex(UserTO user){
		GraphDatabaseService graph = conn.newConnection();
		Index<Node> index = graph.index().forNodes("user");
		Node node = null;
		node = index.get("login", user.getLogin()).getSingle();
		if (node == null) {
			Transaction tx = graph.beginTx();
			try {
				node = graph.createNode();
				node.setProperty("login", user.getLogin());
				node.setProperty("name", user.getName());
				node.setProperty("password", user.getPassword());
				index.add(node, "login", user.getLogin());
				
				tx.success();
				System.out.println("User saved!");
			} catch (Exception e) {
				tx.failure();
				
			} finally {
				tx.finish();
			
				
			}
			
		} else {
			System.out.println("The user has already been registered!");
		}
		graph.shutdown();
	}
	
	
}
